package com.monkeyboy.list;

import com.monkeyboy.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 从尾到头打印链表
 *
 * @Author Gavin
 * @date 2021.04.02 09:53
 */
public class List01 {
    //递归
    public static ArrayList<Integer> print2(ListNode head) {
        ArrayList<Integer> list = new ArrayList<>();
        if (head == null) {
            return list;
        }
        list.addAll(print2(head.next));//添加下一个节点的val
        list.add(head.val);//添加本节点的val
        return list;
    }

    //使用头插法
    public static ListNode print(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode p1 = new ListNode(-1);
        while (head != null) {
            ListNode temp = head.next;
            head.next = p1.next;
            p1.next = head;
            head = temp;
        }
        return p1.next;
    }


    public static void main(String[] args) {
        ListNode p1 = new ListNode(1);
        ListNode p2 = new ListNode(2);
        ListNode p3 = new ListNode(3);
        p1.next = p2;
        p2.next = p3;
        ArrayList<Integer> integers = print2(p1);
        for (Integer pre : integers) {
            System.out.println(pre);
        }
    }
}
